package com.wanxi.Internet;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class InternetWrite {

    public void client() {
        Socket socket = null;
        FileInputStream fileInputStream = null;
        OutputStream outputStream = null;
        try {
            InetAddress inetAddress = InetAddress.getByName("192.168.0.109");
            int port = 1029;
            socket = new Socket(inetAddress, port);


            File file = new File("guidao.jpg");
            fileInputStream = new FileInputStream(file);


            outputStream = socket.getOutputStream();


            byte[] buffer = new byte[1024];
            int len;
            while ((len = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            System.out.println("数据发送完毕");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public void server() {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            int port = 1029;
            serverSocket = new ServerSocket(port);

            socket = serverSocket.accept();

            inputStream = socket.getInputStream();


            File file =new File("dsbfh.jpg");
            fileOutputStream = new FileOutputStream(file);
            byte [] buffer = new byte[1024];
            int len;
            while ((len= inputStream.read(buffer))!=-1){
                fileOutputStream.write(buffer,0,len);
            }
            System.out.println("数据接收完毕");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

        try {
            if(fileOutputStream!=null)
            fileOutputStream.close();
            if(inputStream!=null)
            inputStream.close();
            if ((socket != null))
            socket.close();
            if(serverSocket!=null)
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
